from app.models.database import db
from datetime import datetime

class ExecutionRecord(db.Model):
    """执行记录模型"""
    __tablename__ = 'execution_record'
    
    id = db.Column(db.Integer, primary_key=True)
    scene_id = db.Column(db.Integer, db.ForeignKey('scene.id'), nullable=False)
    environment_id = db.Column(db.Integer, db.ForeignKey('environment.id'))
    status = db.Column(db.String(20), default='pending')  # pending, running, success, failed
    trigger = db.Column(db.String(20), default='manual')  # manual, scheduled, webhook
    start_time = db.Column(db.DateTime, default=datetime.now)
    end_time = db.Column(db.DateTime)
    duration = db.Column(db.Integer)  # 执行时长（毫秒）
    variables = db.Column(db.JSON)  # 执行时的变量
    
    # 关联到场景
    scene = db.relationship('Scene', back_populates='records')
    
    # 关联到环境
    environment = db.relationship('Environment', back_populates='records')
    
    # 关联到执行步骤记录
    steps = db.relationship('ExecutionStepRecord', back_populates='record', order_by='ExecutionStepRecord.start_time')
    
    def to_dict(self):
        return {
            'id': self.id,
            'scene_id': self.scene_id,
            'scene_name': self.scene.name if self.scene else None,
            'environment_id': self.environment_id,
            'environment_name': self.environment.name if self.environment else None,
            'status': self.status,
            'trigger': self.trigger,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S') if self.start_time else None,
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'duration': self.duration,
            'variables': self.variables or {}
        }